package com.cooper.controllers.seller;

import org.springframework.beans.factory.annotation.Autowired;

import com.cooper.constants.DictConstants;
import com.cooper.controllers.LoginRequired;
import com.cooper.core.JsonResult;
import com.cooper.entity.ProjectEntity;
import com.cooper.entity.UserInfo;
import com.cooper.pagination.PageInfo;
import com.cooper.pagination.PageResult;
import com.cooper.service.core.DictService;
import com.cooper.service.project.ProjectService;
import com.cooper.util.BeanUtils;
import com.cooper.util.Controllers;
import com.cooper.vo.ProjectVo;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

@LoginRequired
public class ProjectController {

	@Autowired
	DictService dictService;
	
	@Autowired
	ProjectService projectService;
	
	@Get("edit")
	public String edit(Invocation inv) throws Exception{
		UserInfo userInfo = Controllers.getUserInfo(inv);
		ProjectVo queryParamVo = new ProjectVo();
		queryParamVo.setUserId(userInfo.getId());
		PageInfo pageInfo = new PageInfo();
		PageResult<ProjectVo> ret = projectService.findProjects(queryParamVo, pageInfo);
		ProjectVo project = new ProjectVo();
		if(ret.getPageInfo().getRowCount()>0){
			project = ret.getResult().get(0);
		}
		inv.addModel("projectCategoryList", dictService.getDictList(DictConstants.PROJECT_CATEGORY));
		inv.addModel("project", project);
		return "ProjectEdit";
	}
	
	@Post("save")
	public Object save(Invocation inv,ProjectEntity projectDo) throws Exception{
		UserInfo userInfo = Controllers.getUserInfo(inv);
		JsonResult json = new JsonResult();
		try{
			if(projectDo!=null){
				String fileId = projectDo.getFileId();
				if(projectDo.getId()!=null){
					ProjectEntity pj = projectService.findProjectById(projectDo.getId());
					BeanUtils.copyProperties(projectDo, pj);
					pj.setFileId(fileId);
					pj.setUserId(userInfo.getId());
					projectService.updateProject(pj);
				}else{
					projectDo.setFileId(fileId);
					projectDo.setUserId(userInfo.getId());
					projectService.addProject(projectDo);
				}
				
			}
			json.setSuccess(true);
		}catch(Exception e){
			json.setSuccess(false);
		}
		
		return json;
	}
}
